import { createRouter, createWebHistory } from 'vue-router';
import dashboard from '../pages/dashboard.vue';
import { usetabsStore } from '../store/tabs';
import { useshareStore } from '@/store';

const routes = [
    //基本
    { path: '/', name: '首页', id: '1', meta: { requiresAuth: true, componentNm: 'dashboard' }, query: {}, component: dashboard },
    { path: '/dashboard', name: '首页', id: '1', meta: { requiresAuth: true, componentNm: 'dashboard' }, query: {}, component: dashboard },
    { path: '/login', name: '登陆', id: '0', meta: { componentNm: 'login' }, query: {}, component: () => import('@/pages/auth/login.vue') },
    { path: '/register', name: '注册', id: '0', meta: { componentNm: 'login' }, query: {}, component: () => import('@/pages/auth/login.vue') },
    //基础档案
    { path: '/baseinfo/empinfo', name: '人事档案', id: '2-1', meta: { requiresAuth: true, componentNm: 'empinfo' }, query: {}, component: () => import('@/pages/baseinfo/emp/empinfo.vue') },
    { path: '/baseinfo/empinfo/empinfodetail', name: '人员信息详情', id: '2-1-1', meta: { requiresAuth: true, componentNm: 'empinfodetail' }, query: {}, component: () => import('@/pages/baseinfo/emp/empinfodetail.vue') },
    { path: '/baseinfo/deptinfo', name: '部门档案', id: '2-2', meta: { requiresAuth: true, componentNm: 'deptinfo' }, query: {}, component: () => import('@/pages/baseinfo/deptinfo.vue') },
    { path: '/baseinfo/channelinfo', name: '组织机构', id: '2-3', meta: { requiresAuth: true, componentNm: 'channelinfo' }, query: {}, component: () => import('@/pages/baseinfo/channelinfo.vue') },
    //用户管理
    { path: '/userset/role', name: '角色管理', id: '4-1', meta: { requiresAuth: true, componentNm: 'role' }, query: {}, component: () => import('@/pages/userset/role.vue') },
    { path: '/userset/user', name: '用户管理', id: '4-2', meta: { requiresAuth: true, componentNm: 'user' }, query: {}, component: () => import('@/pages/userset/user.vue') },
    { path: '/userset/operatelog', name: '操作日志', id: '4-3', meta: { requiresAuth: true, componentNm: 'operatelog' }, query: {}, component: () => import('@/pages/userset/operatelog.vue') },
    { path: '/userset/loginlog', name: '登录日志', id: '4-4', meta: { requiresAuth: true, componentNm: 'loginlog' }, query: {}, component: () => import('@/pages/userset/loginlog.vue') },
    { path: '/userset/userapproval', name: '用户审批', id: '4-5', meta: { requiresAuth: true, componentNm: 'userapproval' }, query: {}, component: () => import('@/pages/userset/userapproval.vue') },
    //功能管理
    { path: '/functionset/customsizepage', name: '自定义页面', id: '5-1', meta: { requiresAuth: true, componentNm: 'customsizepage' }, query: {}, component: () => import('@/pages/functionset/customsizepage.vue') },
    { path: '/functionset/customsizepageset', name: '自定义页面设置', id: '5-2', meta: { requiresAuth: true, componentNm: 'customsizepageset' }, query: {}, component: () => import('@/pages/functionset/customsizepageset.vue') },
    { path: '/functionset/permissionset', name: '权限管理', id: '5-3', meta: { requiresAuth: true, componentNm: 'permissionset' }, query: {}, component: () => import('@/pages/functionset/permissionset.vue') },
    { path: '/functionset/menuset', name: '菜单设置', id: '5-4', meta: { requiresAuth: true, componentNm: 'menuset' }, query: {}, component: () => import('@/pages/functionset/menuset.vue') },
    //系统设置
    { path: '/systemsetting/systemparam', name: '系统参数', id: '3-1', meta: { requiresAuth: true, componentNm: 'systemparam' }, query: {}, component: () => import('@/pages/systemsetting/systemparam.vue') },
    { path: '/systemsetting/systemsetting', name: '功能测试', id: '3-2', meta: { requiresAuth: true, componentNm: 'systemsetting' }, query: {}, component: () => import('@/pages/systemsetting/systemsetting.vue') },
    { path: '/:catchAll(.*)', redirect: '/dashboard' }, // 处理所有未定义的路由
];

const router = createRouter({
    history: createWebHistory('/web'),
    routes,
});

// 登录状态检查函数
const isLoggedIn = () => {
    // 这里可以根据你的需求实现登录状态检查
    let userinfo = JSON.parse(localStorage.getItem('user'));
    if (!!userinfo && !!userinfo['token']) {
        // 假设你将用户信息存储在 localStorage 中
        return true;
    } else {
        return false;
    }
};

// 全局前置守卫1
router.beforeEach((to, from, next) => {
    if (to.matched.some((record) => record.meta.requiresAuth)) {
        if (!isLoggedIn()) {
            const tabsStore = usetabsStore();
            tabsStore.setnull();
            next({ name: '登陆' }); // 如果没有登录，重定向到登录页面
        } else {
            if (handtab(to.name)) {
                next(); // 继续导航
            } else {
                console.log('异常');
            }
        }
    } else {
        handtab(to.name);
        next(); // 如果不需要登录，继续导航
    }
});
// 全局前置守卫2
router.beforeResolve(async (to) => {});
// 全局前置守卫3
router.afterEach((to, from) => {
    // 上报流量的操作
    // ...
});

//处理tab数据
const handtab = (key) => {
    //数据有发生改变没有保存，又要跳转到其它页面时候触发操作
    const Stores = useshareStore();
    if (Stores.ischange) {
        const confirmation = window.confirm('数据发生变化还未保存，是否确认要离开');
        if (!confirmation) {
            return false;
        }
        Stores.setischange(false);
    }
    //登录和注册路由不做处理
    if (key !== '登陆' && key !== '注册') {
        let index0 = -1;
        routes.forEach((v, index) => {
            if (v['name'] == key) {
                index0 = index;
                return true;
            }
        });
        if (index0 == -1) {
            return true;
        }
        const tabsStore = usetabsStore();
        Stores.setstoragetab(routes[index0]['meta']['componentNm']); //这是路由缓存组件
        let isexit = false;
        tabsStore.tab.forEach((element) => {
            if (element.id == routes[index0]['id']) {
                isexit = true;
                return true;
            }
        });
        //先获取存储的menu,自定义的name名称不一定是系统默认的
        let item = tabsStore.menu.find((v) => v.path == routes[index0]['path']);
        let menunm = item ? item['name'] : routes[index0]['name'];
        if (!isexit) {
            tabsStore.addtab({
                id: routes[index0]['id'],
                name: menunm,
                path: routes[index0]['path'],
                componentNm: routes[index0]['meta']['componentNm'],
            });
        }
        tabsStore.setActiveTab(menunm);
        tabsStore.setActiveTabindex(routes[index0]['id']);
    }
    return true;
};

export default router;
